package c.x.jy.common.utils;

import static org.quartz.JobBuilder.newJob;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

/**
 *
 * @Description
 */
@SuppressWarnings("all")
public class QuartzManager {
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
    private static String JOB_GROUP_NAME = "MY_JOBGROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "MY_TRIGGERGROUP_NAME";

    /**
     * @Description: 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
     * @param jobName 任务名
     * @param cls 任务
     * @param time 时间设置，参考quartz说明文档
     * qgw 2016年1月21日 下午3:30:10 ^_^
     */
    @SuppressWarnings("unchecked")
    public static void addJob(String jobName, Class<? extends Job> cls, String time,Map<String,Object> data) {
        addJob(jobName,JOB_GROUP_NAME,jobName,TRIGGER_GROUP_NAME,cls,time,data);
    }

    public static void addJob(String jobName,String jobGroupName, Class<? extends Job> cls, String time,Map<String,Object> data) {
        addJob(jobName,jobGroupName,jobName,jobGroupName,cls,time,data);
    }

    /**
     * @Description: 添加一个定时任务
     * @param jobName 任务名
     * @param jobGroupName 任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass 任务
     * @param time 时间设置，参考quartz说明文档
     * qgw 2016年1月21日 下午3:27:00 ^_^
     */
    @SuppressWarnings("unchecked")
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              String time,Map<String,Object> data) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            JobDetail job = newJob(jobClass)
                    .withIdentity(jobName, jobGroupName)
                    .build();
            job.getJobDataMap().putAll(data==null?new HashMap<String, Object>():data);
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            // 按新的cronExpression表达式构建一个新的trigger
            Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(scheduleBuilder).build();
            sched.scheduleJob(job, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 立即运行一次任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @param jobClass
     * @param data
     */
    public static void runJobOnce(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              Map<String,Object> data) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            JobDetail job = newJob(jobClass)
                    .withIdentity(jobName, jobGroupName)
                    .build();
            job.getJobDataMap().putAll(data==null?new HashMap<String, Object>():data);
            SimpleTrigger simpleTrigger =  TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .startAt(new Date())
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                                    .withIntervalInSeconds(3)
                                    .withRepeatCount(0)).build();
            sched.scheduleJob(job, simpleTrigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
     * @param jobName
     * @param time
     * qgw 2016年1月21日 下午3:28:34 ^_^
     */
    @SuppressWarnings("unchecked")
    public static void modifyJobTime(String jobName, String time) {
        TriggerKey triggerKey = TriggerKey.triggerKey(
                jobName, TRIGGER_GROUP_NAME);

        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger =(CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronScheduleBuilder scheduleBuilder =CronScheduleBuilder.cronSchedule(time);
                //按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).startAt(new Date())
                        .withSchedule(scheduleBuilder).build();
                //按新的trigger重新设置job执行
                sched.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     * @param triggerName
     * @param triggerGroupName
     * @param time
     * @author qgw
     * @date 2016年1月27日 下午4:45:15 ^_^
     */
    public static void modifyJobTime(String triggerName,
                                     String triggerGroupName, String time) {
        TriggerKey triggerKey = TriggerKey.triggerKey(
                triggerName, triggerGroupName);
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                // trigger已存在，则更新相应的定时设置
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                        .cronSchedule(time);
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).startAt(new Date())
                        .withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                sched.resumeTrigger(triggerKey);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void removeJob(String jobName){
        removeJob(jobName,JOB_GROUP_NAME,TRIGGER_GROUP_NAME);
    }

    public static void removeJob(String jobName,String jobGroupName){
        removeJob(jobName,jobGroupName,jobGroupName);
    }

    /**
     * @Description 移除一个任务(使用默认的任务组名，触发器名，触发器组名)
     * @param jobName
     * @author qgw
     * @date 2016年1月29日 下午2:21:16 ^_^
     */
    public static void removeJob(String jobName,String jobGroupName,String triggerGroupName) {
        TriggerKey triggerKey = TriggerKey.triggerKey(
                jobName, triggerGroupName);
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            Trigger trigger = (Trigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            sched.pauseTrigger(triggerKey);;// 停止触发器
            sched.unscheduleJob(triggerKey);// 移除触发器
            sched.deleteJob(jobKey);// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * @Description:暂停一个任务
     * @param jobName
     * @param jobGroupName
     * qgw 2016年1月22日 下午4:24:55 ^_^
     */
    public static void pauseJob(String jobName, String jobGroupName) {
        JobKey jobKey =JobKey.jobKey(jobName, jobGroupName);
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.pauseJob(jobKey);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * @Description:暂停一个任务(使用默认组名)
     * @param jobName
     * qgw 2016年1月22日 下午4:24:55 ^_^
     */
    public static void pauseJob(String jobName) {
        JobKey jobKey =JobKey.jobKey(jobName, JOB_GROUP_NAME);
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Description:启动所有定时任务
     * @author qgw
     * @date 2016年1月29日 下午2:21:16 ^_^
     */
    public static void startJobs() {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description 关闭所有定时任务
     * @author qgw
     * @date 2016年1月25日 下午2:26:54 ^_^
     */
    public static void shutdownJobs() {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static List<DCASJob> getAllJob(String jobGroupName){
        List<DCASJob> list = new ArrayList();
        try {
            if(jobGroupName==null){
                jobGroupName = JOB_GROUP_NAME;
            }
            Scheduler sched = gSchedulerFactory.getScheduler();
            Set<JobKey> jobKeys = sched.getJobKeys(GroupMatcher.<JobKey>groupEquals(jobGroupName));
            for(JobKey jobKey : jobKeys){
                Trigger trigger = sched.getTriggersOfJob(jobKey).get(0);
                Date nextFireTime = trigger.getNextFireTime();
                Date previousFireTime = trigger.getPreviousFireTime();
                Date startTime = trigger.getStartTime();
                Date endTime = trigger.getEndTime();
                System.out.println("job_name:"+jobKey.getName()+"|job_group:"+jobKey.getGroup()+"|");
                DCASJob job = new DCASJob(jobKey.getName(),jobKey.getGroup(),nextFireTime,previousFireTime,startTime,endTime);
                list.add(job);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    public static class DCASJob{
        private String name;
        private String group;
        private Date nextFireTime;
        private Date previousFireTime;
        private Date startTime;
        private Date endTime;

        public DCASJob(String name, String group, Date nextFireTime, Date previousFireTime, Date startTime, Date endTime) {
            this.name = name;
            this.group = group;
            this.nextFireTime = nextFireTime;
            this.previousFireTime = previousFireTime;
            this.startTime = startTime;
            this.endTime = endTime;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGroup() {
            return group;
        }

        public void setGroup(String group) {
            this.group = group;
        }

        public Date getNextFireTime() {
            return nextFireTime;
        }

        public void setNextFireTime(Date nextFireTime) {
            this.nextFireTime = nextFireTime;
        }

        public Date getPreviousFireTime() {
            return previousFireTime;
        }

        public void setPreviousFireTime(Date previousFireTime) {
            this.previousFireTime = previousFireTime;
        }

        public Date getStartTime() {
            return startTime;
        }

        public void setStartTime(Date startTime) {
            this.startTime = startTime;
        }

        public Date getEndTime() {
            return endTime;
        }

        public void setEndTime(Date endTime) {
            this.endTime = endTime;
        }
    }

}
